package com.springboot.util;

import static java.lang.reflect.Array.get;
import static java.lang.reflect.Array.getLength;
import static org.springframework.beans.BeanUtils.instantiate;
import static org.springframework.util.CollectionUtils.isEmpty;

import java.io.Serializable;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import org.springframework.beans.BeanWrapper;
import org.springframework.beans.BeanWrapperImpl;

import com.springboot.enums.ValueEnum;


/**
 * 实体工具
 * 
 * @author fuzy
 *
 */
public final class EntityUtils
{
    private EntityUtils()
    {

    }

    /**
     * 根据类型构建对象
     * 
     * @param clazz 对象类型
     * @param <T> 对象类型
     * @return 对象
     */
    public static <T> T newInstance(Class<T> clazz)
    {
        T entity;
        try
        {
            entity = clazz.newInstance();
        }
        catch (Exception e)
        {
            entity = null;
        }
        return entity;
    }

    /**
     * 对象拷贝 数据对象空值不拷贝到目标对象
     * 
     * @param src 源对象
     * @param dest 目标对象
     */
    public static void copyBeanNotNull2Bean(Object src, Object dest)
    {
        BeanWrapper destWrapper = new BeanWrapperImpl(dest);
        List<Field> fieldList = new ArrayList<>();
        // 包括父类属性
        Class<?> clazz = src.getClass();
        while (clazz != Object.class)
        {
            Field[] fields = clazz.getDeclaredFields();
            fieldList.addAll(Arrays.asList(fields));
            clazz = clazz.getSuperclass();
        }
        for (Field field : fieldList)
        {
            field.setAccessible(true);
            String fieldName = field.getName();
            try
            {
                Object value = field.get(src);
                if (destWrapper.getPropertyDescriptor(fieldName) != null && value != null)
                {
                    destWrapper.setPropertyValue(fieldName, value);
                }
            }
            catch (Exception e)
            {
            }
        }
    }

    /**
     * 获取所有非静态字段
     * 
     * @param clazz
     * @param fieldList
     */
    public static void getFieldList(Class<?> clazz, List<Field> fieldList)
    {
        if (clazz == Object.class)
        {
            return;
        }
        Field[] fields = clazz.getDeclaredFields();
        if (fields != null && fields.length > 0)
        {
            for (Field field : fields)
            {
                int modifier = field.getModifiers();
                if (Modifier.isStatic(modifier))
                {
                    continue;
                }
                fieldList.add(field);
            }
        }
        getFieldList(clazz.getSuperclass(), fieldList);
    }

    /**
     * 获取对象的属性值
     * 
     * @param obj 对象
     * @param fieldName 属性名
     * @return 属性值
     */
    @SuppressWarnings("unchecked")
    public static <T> T getFieldValue(Class<?> clazz, Object obj, String fieldName)
    {
        T value = null;
        if (clazz == null)
        {
            clazz = obj.getClass();
        }
        try
        {
            Field field = clazz.getDeclaredField(fieldName);
            field.setAccessible(true);
            value = (T) field.get(obj);
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
        return value;
    }

    /**
     * 将map数据转换成对应的实体类对象
     * 
     * @param <T> 实体类
     * @param clazz 实体类
     * @param dataList 数据
     * @return 对象
     */
    public static <T extends Serializable> List<T> convertData(Class<T> clazz, List<Map<String, Object>> dataList)
    {
        if (isEmpty(dataList))
        {
            return null;
        }
        List<T> entryList = new ArrayList<>();
        for (Map<String, Object> dataMap : dataList)
        {
            entryList.add(addEntity(clazz, dataMap));
        }
        return entryList;
    }

    /**
     * 将map中的值赋给对象
     * 
     * @param <T> 实体类
     * @param clazz 实体类
     * @param dataMap 数据
     * @return 对象
     */
    public static <T extends Serializable> T addEntity(Class<T> clazz, Map<String, Object> dataMap)
    {
        T t = instantiate(clazz);
        BeanWrapper wrapper = new BeanWrapperImpl(t);
        Field[] fields = clazz.getDeclaredFields();
        for (Field field : fields)
        {
            field.setAccessible(true);
            String fieldName = field.getName();
            if (dataMap.containsKey(fieldName))
            {
                wrapper.setPropertyValue(fieldName, dataMap.get(fieldName));
            }
        }
        return t;
    }

    /**
     * 集合toString
     * 
     * @param builder StringBuilder
     * @param col 集合
     * @param <T> 任意类型
     */
    public static <T> void toString(StringBuilder builder, Collection<T> col)
    {
        if (col == null || col.isEmpty())
        {
            builder.append(col);
        }
        else
        {
            builder.append('[');
            for (T t : col)
            {
                if (t instanceof Collection)
                {
                    toString(builder, (Collection<?>) t);
                }
                else if (t instanceof Map)
                {
                    toString(builder, (Map<?, ?>) t);
                }
                else
                {
                    toString(builder, t);
                }
                builder.append(", ");
            }
            builder.delete(builder.lastIndexOf(", "), builder.length());
            builder.append(']');
        }
    }

    /**
     * map toString
     * 
     * @param builder StringBuilder
     * @param map Map
     * @param <K> key
     * @param <V> value
     */
    public static <K, V> void toString(StringBuilder builder, Map<K, V> map)
    {
        if (map == null || map.isEmpty())
        {
            builder.append(map);
        }
        else
        {
            V v;
            builder.append('{');
            for (Entry<K, V> entry : map.entrySet())
            {
                builder.append(entry.getKey()).append('=');
                if ((v = entry.getValue()) instanceof Collection)
                {
                    toString(builder, (Collection<?>) v);
                }
                else if (v instanceof Map)
                {
                    toString(builder, (Map<?, ?>) v);
                }
                else
                {
                    toString(builder, v);
                }
                builder.append(", ");
            }
            builder.delete(builder.lastIndexOf(", "), builder.length());
            builder.append('}');
        }
    }

    /**
     * toString
     * 
     * @param builder StringBuilder
     * @param object 对象
     */
    public static void toString(StringBuilder builder, Object object)
    {
        if (object == null)
        {
            builder.append(object);
        }
        else
        {
            Class<?> clazz = object.getClass();
            if (clazz.isArray())
            {
                builder.append('[');
                int n = getLength(object);
                if (n > 0)
                {
                    for (int i = 0; i < n; i++)
                    {
                        toString(builder, get(object, i));
                        builder.append(", ");
                    }
                    builder.delete(builder.lastIndexOf(", "), builder.length());
                }
                builder.append(']');
            }
            else if (object instanceof Collection)
            {
                toString(builder, (Collection<?>) object);
            }
            else if (object instanceof Map)
            {
                toString(builder, (Map<?, ?>) object);
            }
            else
            {
                builder.append(object);
            }
        }
    }

    /**
     * 获取枚举对象
     * 
     * @param clazz 枚举类
     * @param value 枚举值
     * @return 枚举对象
     */
    public static Object getEnumValue(Class<?> clazz, String value)
    {
        if (ValueEnum.class.isAssignableFrom(clazz))
        {
            @SuppressWarnings("unchecked")
            Class<ValueEnum> c = (Class<ValueEnum>) clazz;
            for (ValueEnum ve : c.getEnumConstants())
            {
                if (ve.getValue().equals(value))
                {
                    return ve;
                }
            }
        }
        else
        {
            for (Object o : clazz.getEnumConstants())
            {
                if (o.toString().equals(value))
                {
                    return o;
                }
            }
        }
        return null;
    }

}
